<template>
  <div class="layout-container">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapsed ? '64px' : '240px'" class="sidebar">
      <div class="sidebar-header">
        <div class="logo" @click="toggleCollapse">
          <el-icon><Setting /></el-icon>
          <span v-show="!isCollapsed" class="logo-text">工单管理系统</span>
        </div>
      </div>
      
      <el-menu
        :default-active="activeMenuKey"
        :collapse="isCollapsed"
        :unique-opened="true"
        class="sidebar-menu"
        @select="handleMenuSelect"
        router
      >
        <template v-for="item in filteredMenuItems" :key="item.key">
          <!-- 有子菜单的项目 -->
          <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.key">
            <template #title>
              <el-icon><component :is="item.icon" /></el-icon>
              <span>{{ item.title }}</span>
            </template>
            <el-menu-item
              v-for="child in item.children"
              :key="child.key"
              :index="child.path"
            >
              <el-icon><component :is="child.icon" /></el-icon>
              <span>{{ child.title }}</span>
            </el-menu-item>
          </el-sub-menu>
          
          <!-- 没有子菜单的项目 -->
          <el-menu-item v-else :index="item.path">
            <el-icon><component :is="item.icon" /></el-icon>
            <span>{{ item.title }}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </el-aside>
    
    <!-- 主内容区域 -->
    <el-container class="main-container">
      <!-- 顶部导航栏 -->
      <el-header class="top-header">
        <div class="header-left">
          <el-button 
            type="text" 
            @click="toggleCollapse"
            class="collapse-btn"
          >
            <el-icon><Expand v-if="isCollapsed" /><Fold v-else /></el-icon>
          </el-button>
          
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item 
              v-for="(item, index) in breadcrumbItems" 
              :key="index"
              :to="index < breadcrumbItems.length - 1 ? item.path : undefined"
            >
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="header-right">
          <!-- 通知图标 -->
          <el-badge :value="notificationsStore.unreadCount" :hidden="notificationsStore.unreadCount === 0" class="notification-badge">
            <el-button 
              type="text" 
              @click="goToNotifications"
              class="notification-btn"
              title="通知中心"
            >
              <el-icon><Bell /></el-icon>
            </el-button>
          </el-badge>
          
          <!-- 用户信息下拉菜单 -->
          <el-dropdown @command="handleUserCommand">
            <span class="user-info">
              <el-avatar :size="32" :src="authStore.user?.avatarUrl">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span v-show="!isCollapsed" class="user-name">{{ authStore.userDisplayName }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item 
                  v-if="authStore.hasPermission('system:config')"
                  command="settings"
                >
                  <el-icon><Setting /></el-icon>
                  系统设置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <!-- 主题切换 -->
          <ThemeToggle />
        </div>
      </el-header>
      
      <!-- 主内容 -->
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, computed, watch, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '../store/auth'
import { useNotificationsStore } from '../store/notifications'
import { getFilteredMenuItems, getBreadcrumbItems } from '../config/menu'
import ThemeToggle from './ThemeToggle.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ChartCleanup from '../utils/chartCleanup'
import { 
  Setting, 
  Expand, 
  Fold, 
  Bell, 
  User, 
  ArrowDown, 
  SwitchButton 
} from '@element-plus/icons-vue'

export default {
  name: 'AppLayout',
  components: {
    ThemeToggle
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const authStore = useAuthStore()
    const notificationsStore = useNotificationsStore()
    
    // 组件卸载标志位，防止组件销毁后的异步更新
    const isUnmounted = ref(false)
    
    // 侧边栏折叠状态
    const isCollapsed = ref(false)
    
    // 根据用户角色和权限过滤菜单
    const filteredMenuItems = computed(() => {
      if (!authStore.isAuthenticated || !authStore.role) {
        return []
      }
      return getFilteredMenuItems(authStore.role, authStore.permissions)
    })
    
    // 当前激活的菜单项
    const activeMenuKey = computed(() => {
      const currentPath = route.path
      const flattenedItems = filteredMenuItems.value.flatMap(item => 
        item.children ? [item, ...item.children] : [item]
      )
      const currentItem = flattenedItems.find(item => item.path === currentPath)
      return currentItem?.key || currentPath
    })
    
    // 面包屑导航
    const breadcrumbItems = computed(() => {
      if (!authStore.isAuthenticated || !authStore.role) {
        return []
      }
      return getBreadcrumbItems(route.path, authStore.role, authStore.permissions)
    })
    
    // 切换侧边栏折叠状态
    const toggleCollapse = () => {
      isCollapsed.value = !isCollapsed.value
      // 保存到localStorage
      localStorage.setItem('sidebar-collapsed', isCollapsed.value.toString())
    }
    
    // 处理菜单选择
    const handleMenuSelect = (path) => {
      router.push(path)
    }
    
    // 处理用户命令
    const handleUserCommand = async (command) => {
      switch (command) {
        case 'profile':
          router.push('/personal-center')
          break
        case 'settings':
          router.push('/system-settings')
          break
        case 'logout':
          await handleLogout()
          break
      }
    }
    
    // 跳转到通知中心
    const goToNotifications = () => {
      router.push('/notifications')
    }
    
    // 处理登出
    const handleLogout = async () => {
      try {
        await ElMessageBox.confirm(
          '确定要退出登录吗？',
          '确认退出',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 清理所有图表实例
        await ChartCleanup.cleanupAllCharts()
        
        authStore.logout()
        ElMessage.success('已退出登录')
        
        // 延迟跳转，确保清理完成
        setTimeout(() => {
          router.push('/login')
        }, 100)
      } catch (error) {
        // 用户取消或其他错误
        if (error !== 'cancel') {
          console.error('Logout error:', error)
        }
      }
    }
    
    // 初始化侧边栏状态
    const initSidebarState = () => {
      const savedState = localStorage.getItem('sidebar-collapsed')
      if (savedState !== null) {
        isCollapsed.value = savedState === 'true'
      }
    }
    
    // 监听路由变化，更新面包屑
    watch(() => route.path, () => {
      // 路由变化时，面包屑会自动更新
      // 检查组件是否已卸载
      if (isUnmounted.value) {
        return
      }
    })
    
    // 组件卸载前的清理
    onBeforeUnmount(() => {
      console.log('🧹 AppLayout组件即将卸载，执行清理操作...')
      
      // 设置卸载标志
      isUnmounted.value = true
      
      // 清理所有图表实例（如果有）
      try {
        ChartCleanup.cleanupAllCharts()
      } catch (error) {
        console.warn('清理图表时出错:', error)
      }
      
      // 这里可以添加其他需要清理的资源
      // 例如：取消pending的请求、清理事件监听器等
      
      console.log('✅ AppLayout组件清理完成')
    })
    
    // 初始化
    initSidebarState()
    
    return {
      isCollapsed,
      filteredMenuItems,
      activeMenuKey,
      breadcrumbItems,
      authStore,
      notificationsStore,
      toggleCollapse,
      handleMenuSelect,
      handleUserCommand,
      goToNotifications,
      handleLogout
    }
  }
}
</script>

<style scoped>
.layout-container {
  display: flex;
  height: 100vh;
  background-color: var(--bg-primary);
}

.sidebar {
  background-color: var(--bg-primary);
  border-right: 1px solid var(--border-primary);
  transition: width 0.3s ease;
  overflow: hidden;
}

.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid var(--border-primary);
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  font-size: 18px;
  font-weight: 700;
  color: var(--text-primary);
  transition: all 0.3s ease;
}

.logo:hover {
  color: #409eff;
}

.logo-text {
  white-space: nowrap;
  overflow: hidden;
}

.sidebar-menu {
  border-right: none;
  height: calc(100vh - 60px);
  overflow-y: auto;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 240px;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.top-header {
  height: 60px;
  background-color: var(--bg-primary);
  border-bottom: 1px solid var(--border-primary);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.collapse-btn {
  font-size: 18px;
  color: var(--text-primary);
}

.breadcrumb {
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.notification-badge {
  margin-right: 8px;
}

.notification-btn {
  font-size: 18px;
  color: var(--text-primary);
  transition: color 0.2s;
}

.notification-btn:hover {
  color: #409eff;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  cursor: pointer;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: var(--bg-tertiary);
}

.user-name {
  font-weight: 500;
  color: var(--text-primary);
}

.main-content {
  padding: 20px;
  background-color: var(--bg-secondary);
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;
    height: 100vh;
  }
  
  .main-container {
    margin-left: 0;
  }
  
  .top-header {
    padding: 0 16px;
  }
  
  .main-content {
    padding: 16px;
  }
}

/* 暗色主题适配 */
.dark .sidebar {
  background-color: var(--bg-primary);
  border-right-color: var(--border-primary);
}

.dark .top-header {
  background-color: var(--bg-primary);
  border-bottom-color: var(--border-primary);
}

.dark .main-content {
  background-color: var(--bg-secondary);
}
</style>
